package com.user.controller;

import com.user.service.UserService;
import com.user.userUtils.tokenUtils;
import com.wukc.springcloud.domain.CommonResult;
import com.wukc.springcloud.domain.user.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wukc
 * @Description: TODO
 * @DateTime: 2022/9/1 15:10
 **/
@RestController
@Slf4j
@CrossOrigin
public class UserController {
    @Resource
    private UserService userService;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/user/createUser")
    public CommonResult create(@RequestBody User user)
    {
        int result = userService.createUser(user);
        log.info("*****插入结果："+result);

        if(result > 0)
        {
            return new CommonResult(200,"插入数据库成功,serverPort: "+serverPort,result);
        }else{
            return new CommonResult(444,"插入数据库失败",null);
        }
    }

    @GetMapping(value = "/user/getUserById/{id}")
    public CommonResult<User> getUserById(@PathVariable("id") Long id)
    {
        User user = userService.getUserById(id);

        if(user != null)
        {
            return new CommonResult(200,"查询成功,serverPort:  "+serverPort,user);
        }else{
            return new CommonResult(444,"没有对应记录,查询ID: "+id,null);
        }
    }

    @GetMapping(value = "/user/getUserByName/{userName}")
    public CommonResult<User> getUserByName(@PathVariable("userName") String userName)
    {
        User user = userService.getUserByName(userName);

        if(user != null)
        {
            return new CommonResult(200,"查询成功,serverPort:  "+serverPort,user);
        }else{
            return new CommonResult(444,"没有对应记录,查询名称: "+userName,null);
        }
    }

    @PostMapping(value = "/user/login")
    public CommonResult login(@RequestBody Map userLoginInfo){
        User user = userService.getUserByName(userLoginInfo.get("userName").toString());
        if(user != null){
            if(user.getPassword().equals(userLoginInfo.get("passWord").toString())){
                HashMap map = new HashMap();
                map.put("userInfo",user);
                map.put("token",tokenUtils.createToken(user.getId(),1));
                return new CommonResult(200,"登录成功",map);
            }else{
                return new CommonResult(444,"用户名或密码错误:  ",null);
            }
        }else{
            return new CommonResult(444,"用户未注册： 用户名称为 "+userLoginInfo.get("userName"),null);
        }
    };

    @GetMapping(value = "/test/lb")
    public CommonResult getUserLB()
    {
        return new CommonResult(200,"老王傻逼  端口是："+serverPort,null);
    }
}
